<!-- eslint-disable vue/max-attributes-per-line -->
<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm
        :searchFunc="searchFunc" :resetFunc="() => {
          searchData = {};
          vdata.startEndTime = null
        }
        " searchConditionNum="7"
        style="color:#666666;"
      >
        <a-form-item class="table-search-item" label="机构选择">  
          <GzTreeSelect ref="gzThreeRef" v-model:value="searchData['agentNo']" :isNeedDefault="false" />
        </a-form-item>
        <a-form-item class="table-search-item" label="商户名">  
          <a-input v-model:value="searchData['mchName']" label="商户名" :placeholder="'请输入商户简称/全称'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="商户号">  
          <a-input v-model:value="searchData['mchNo']" label="商户号" :placeholder="'请输入商户号'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="商户状态">
          <a-select v-model:value="searchData['state']" :placeholder="'请选择商户状态'">
            <a-select-option :value="0">停用</a-select-option>
            <a-select-option :value="1">正常</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item class="table-search-item" label="当前通道">
          <a-input v-model:value="searchData['ifName']" label="当前通道" :placeholder="'请输入通道'" />
        </a-form-item>
        <a-form-item class="table-search-item" style="width: 350px;" label="进件日期">
          <a-range-picker v-model:value="vdata.startEndTime" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" />
        </a-form-item>
      </GzSearchForm>

      <!-- 列表渲染 -->
      <GzTable
        ref="infoTable" :init-data="true" :req-table-data-func="reqTableDataFunc" :table-columns="tableColumns"
        :search-data="searchData" row-key="mchNo" @btnLoadClose="btnLoading = false"
      >
        <template #topBtnSlot>
          <div
            style="
              display: flex;
              gap: 10px;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <GzUploadExe v-if="$access('ENT_MCH_INFO_IMPT_MCH')" :isTrue="true" :showUploadList="false" @updateValue="handleUpdate">
              <a-button type="primary" style="margin: 0" @click="toLeadInto">
                <plus-outlined />导入商户
              </a-button>
            </GzUploadExe>
            <!-- <a-button v-if="$access('ENT_MCH_INFO_DOWN_TEMPLATE')" type="link" href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/211885cf-c22e-476f-9586-0dd9bdcce079.xlsx" style="margin: 0;">
              下载导入商户模板
            </a-button> -->
            <a-button v-if="$access('ENT_MCH_INFO_DOWN_TEMPLATE')" type="link" href="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/henan/download/b531b615-39ab-4657-a47a-ab9749d0896e.xlsx" style="margin: 0;">
              下载导入商户模板
            </a-button>
            <span>共计:{{ vdata.totalMch }}户商户</span>

            <!-- <a-button type="link" style="margin: 0;" @click="openDialog">
              查看本次导入结果
            </a-button> -->
            <!-- <a-button type="primary" @click="toLeadInto" style="margin: 0">
              <EyeOutlined />查看错误
            </a-button> -->
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orgName'">
            <span>{{ record.cityName || '' }}/{{ record.areaNameNew || '' }}/{{ record.orgName || '' }}</span>
          </template>

          <template v-if="column.key === 'agentNo'">
            <span>{{ record.agentNo }}</span>
          </template>

          <!-- <template v-if="column.key === 'mchName' && $access('ENT_MCH_INFO_VIEW')">
            <a @click="detailFunc(record.mchNo)"><b>{{ record.mchName }}</b></a>
          </template> -->

          <template v-if="column.key == 'mchListImage'">
            <a-image v-if="record.mchListImage" :src="record.mchListImage" style="width: 80px;" />
            <img v-else src="@/assets/svg/default-img.svg" style="width: 80px;">
          </template>

          <template v-if="column.key === 'orderSort'">
            {{ record.orderSort === 1 ? '是' : '否' }}
          </template>

          <template v-if="column.key === 'ossRecordId'">
            <a-badge :text="record.ossRecordId ? '老商户' : '新商户'" />
          </template>

          <template v-if="column.key === 'state'">
            <a-badge :status="record.state === 0 ? 'error' : 'processing'" :text="record.state === 0 ? '禁用' : '启用'" />
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <GzTableColumns>
              <!-- <GzUploadExe v-if="$access('ENT_MCH_INFO_IMG')" :showUploadList="false" :isNeedImport="false" :accept="'.jpg,.png,.jpeg,.gif,.JPG,.PNG,.JPEG,.GIF'" @sendData="(src) => uploadMchImg(src, record.mchNo)">
                <template #uploadBtn>
                  <a-button type="link">{{ record.mchListImage? '更新图片' : '新增图片' }}</a-button>
                </template>
              </GzUploadExe>
              <a-button v-if="$access('ENT_MCH_INFO_ORDER')" type="link" :danger="record.orderSort === 1" @click="toTopHandle(record)">{{ record.orderSort === 1 ? '取消置顶' : '精选置顶' }}</a-button> -->
              <a-button v-if="$access('ENT_MCH_INFO_EDIT')" type="link" @click="mchInfoUpdate(record)">商户信息/修改</a-button>
              <a-button v-if="$access('ENT_MCH_INFO_VIEW')" type="link" @click="channelInfo(record)">通道信息</a-button> 
              <!-- <a-button v-if="$access('ENT_MCH_INFO_ORDER')" type="link" @click="channelCodeDownLoad(record)">渠道码查看/下载</a-button>  -->
            </GzTableColumns>
          </template>
        </template>
      </GzTable>
    </a-card>
    <!-- 详情页面组件  -->
    <InfoDetail ref="infoDetail" :callback-func="searchFunc" />
    <!-- 本次导入数据信息结果展示 -->
    <ResultModel :visible="vdata.visible" :errData="vdata.errData" @closeModal="closeModal" />
    <!-- 渠道码 -->
    <a-modal
      v-model:visible="open"
      :footer="null"
      :bodyStyle="{
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
      }"
    >
      <a-image :width="200" :src="codeUrl" />
      <div>{{ vdata.channelRecord.channelCode }}</div>
      <div>{{ vdata.channelRecord.appName }}</div>
      <div>【 {{ useAgentStore().hostname }} 】</div>
    </a-modal>

    <!-- 新增修改 -->
    <AddOrEdit ref="addOrEditRef" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import{$getMchList,$updateMchImage,$topMch,$apiMchInfoImport}from  '@/api/mch/index'
import { generateChannelCode } from '@/views/channel/channelUtils'
import InfoDetail from './Detail.vue'
import AddOrEdit from './AddOrEdit.vue'
import ResultModel from './ResultModel.vue'
import { ref, reactive, getCurrentInstance } from 'vue'
import { useAgentStore } from '@/store/modules/agent'
const open = ref(false)
const codeUrl = ref('')
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const infoDetail = ref()
const infoTable = ref()
const addOrEditRef = ref()

const vdata:any = reactive({
  startEndTime:null,
  visible:false,
  errMsg:[],
  totalMch:'',
  channelRecord: null,  // 选择的渠道记录
})
let tableColumns = reactive([
{ key: 'mchNo', title: '商户号', dataIndex: 'mchNo', width: 150, minWidth: 150, maxWidth: 200, },
{ key: 'wechatSubmerchantNo', title: '微信商户号', dataIndex: 'wechatSubmerchantNo', width: 150, minWidth: 150, maxWidth: 200, },
{ key: 'aliSubmerchantNo', title: '支付宝商户号', dataIndex: 'aliSubmerchantNo', width: 160, minWidth: 160, maxWidth: 200, },
{ key: 'ysfSubmerchantNo', title: '云闪付商户号', dataIndex: 'ysfSubmerchantNo', width: 150, minWidth: 150, maxWidth: 200, },
{ key: 'mchShortName', title: '商户简称', dataIndex: 'mchShortName', width: 350, minWidth: 350, maxWidth: 400, },
{ key: 'channelCreatedAt', title: '商户进件日期', dataIndex: 'channelCreatedAt', width: 250, minWidth: 250, maxWidth: 300, },
{ key: 'orgName', title: '商户归属网点', dataIndex: 'orgName', width: 350, minWidth: 350, maxWidth: 350,  },
{ key: 'areaNameNew', title: '商户归属区县', dataIndex: 'areaNameNew', width: 150, minWidth: 150, maxWidth: 200,  },
{ key: 'ifName', title: '当前通道', dataIndex: 'ifName', width: 150, minWidth: 150, maxWidth: 250, },
{ key: 'state', title: '状态', dataIndex: 'state', width: 80, minWidth: 80, maxWidth: 150 },
{ key: 'operation', title: '操作', width: 360, fixed: 'right', align: 'center' }
])

let btnLoading = ref(false)
let searchData = ref({})

// 请求table接口数据
function reqTableDataFunc(params: any) {
  params.startTime = vdata.startEndTime ? vdata.startEndTime[0] : ''
  params.endTime = vdata.startEndTime ? vdata.startEndTime[1] : ''
  return new Promise((resolve,reject)=>{
    $getMchList(params).then(res=>{
      vdata.totalMch = res.total
      resolve(res)
    })
  }
  )
}
function searchFunc() {
  // 点击【查询】按钮点击事件
  infoTable.value.refTable(true)
}

// 商户信息/修改
const mchInfoUpdate = (record) =>{
  addOrEditRef.value.show(record)
}
// 通道信息
const channelInfo = (record) =>{
  infoDetail.value.show(record.mchNo)
}
// 渠道码查看/下载
const channelCodeDownLoad = async (record) =>{
  console.log(record,'渠道码查看/下载')
  const url = await generateChannelCode(`${useAgentStore().channelBaseUrl}?channelId=${record.activityChannelId}&channelType=${record.channelType}`)
  codeUrl.value = url
  vdata.channelRecord = record
  open.value = true
}

// 导入成功后打开结果弹窗
async function handleUpdate (value){
  $apiMchInfoImport({ossFileUrl:value}).then(res=>{
    if(res){
      const url = res
      const link = document.createElement('a')
      link.href = url
      link.download = 'filename.xlsx' // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      searchFunc()
    }else{
      $infoBox.message.success('此次导入商户无异常数据')
      searchFunc()
    }
  })
}


// 查看本次导入商户异常信息
const openDialog = () =>{
  vdata.visible = true
}

// 关闭弹窗
const closeModal = (value)=>{
  console.log(value,'关闭弹窗')
  vdata.visible = value
}

/**
 * 商户图片修改
 */
const uploadMchImg = async (imageUrl,mchNo) => {
  await $updateMchImage({ imageUrl, mchNo })
  infoTable.value.refTable()
  $infoBox.message.success('商户图片修改成功！')
}
/**
 * 精选商户置顶
 */
const toTop = async (mchNo, order, flag) => {
  await $topMch({ mchNo, order })
  infoTable.value.refTable(true)
  $infoBox.message.success(flag ? '商户置顶成功！' : '商户取消置顶！')
}

/**
 * 置顶提示
 */
const toTopHandle = (record) => {
  const { mchNo, orderSort } = record
  if(orderSort === 1){  // 已置顶 去取消置顶
    $infoBox.confirm('确认取消置顶？', '请确认是否取消置顶当前商户？', () => {
      toTop(mchNo, 0, false)
    })
  }else{  // 未置顶 去置顶
    $infoBox.confirm('确认置顶？', '请确认是否置顶当前商户？', () => {
      toTop(mchNo, 1, true)
    })
  }
}

// 导入商户
function toLeadInto() {
  // 、、
}
</script>
<style>
  .ant-form-item-label{
    color:#666 !important;
  }
</style>
